package com.aiju.cash.ui.pic;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.cash.R;
import com.aiju.common.thread.AsyncExecutor;
import com.aiju.support.recyclerView.DividerGridItemDecoration;
import com.bumptech.glide.Glide;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.kevin.crop.UCrop;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author: 佐为
 * @date: 2016-11-18 14:03
 * @version: V1.0
 * @Description: 描述
 */
public class SelectActivity extends BaseTitleActivity {

    private static final int GALLERY_REQUEST_CODE = 0;    // 相册选图标记
    private static final int CAMERA_REQUEST_CODE = 1;    // 相机拍照标记

    // 拍照临时图片
    private String mTempPhotoPath;
    // 剪切后图像文件
    private Uri mDestinationUri;

    private final static int SCAN_OK = 1;
    private RecyclerView mRecyclerView;

    private PicAdapter mPicAdapter;
    private RecyclerAdapterWithHF mRecyclerAdapterWithHF;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SCAN_OK:
                    mPicAdapter = new PicAdapter(SelectActivity.this, (List<String>) msg.obj);
                    mRecyclerAdapterWithHF = new RecyclerAdapterWithHF(mPicAdapter);
                    //mRecyclerView.setLayoutManager(new LinearLayoutManager(SelectActivity.this));
                    mRecyclerView.setLayoutManager(new GridLayoutManager(SelectActivity.this, 3));
                    //设置分隔线
                    //mRecyclerView.addItemDecoration(new DividerItemDecoration(SelectActivity.this, DividerItemDecoration.VERTICAL_LIST, R.drawable.shape_list_divider_h5));
                    mRecyclerView.addItemDecoration(new DividerGridItemDecoration(SelectActivity.this));
                    mRecyclerView.setAdapter(mRecyclerAdapterWithHF);
                    mRecyclerAdapterWithHF.setOnItemClickListener(new RecyclerAdapterWithHF.OnItemClickListener() {
                        @Override
                        public void onItemClick(RecyclerAdapterWithHF adapter, RecyclerView.ViewHolder vh, int position) {

                            if (position == 0) {
                                //照相机
                                Intent photoIn = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                photoIn.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mTempPhotoPath)));
                                startActivityForResult(photoIn, CAMERA_REQUEST_CODE);
                            } else {
                                //裁剪
                                startCropActivity(Uri.fromFile(new File(mPicAdapter.filePath.get(position))));
                            }
                        }
                    });
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_pic);

        mRecyclerView = (RecyclerView) findViewById(R.id.rv_pic);
        getImage();
        //
    }


    //检索本地图
    private void getImage() {
        mDestinationUri = Uri.fromFile(new File(getCacheDir(), "cropImage.jpeg"));
        mTempPhotoPath = Environment.getExternalStorageDirectory() + File.separator + "photo.jpeg";
        AsyncExecutor.createTaskDistributor().execute(new Runnable() {
            @Override
            public void run() {
                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = SelectActivity.this.getApplicationContext().getContentResolver();

                //只查询jpeg和png的图片
                Cursor mCursor = mContentResolver.query(mImageUri, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png"}, MediaStore.Images.Media.DATE_MODIFIED);

                if (mCursor == null) {
                    return;
                }

                List<String> images = new ArrayList<String>();
                while (mCursor.moveToNext()) {
                    //获取图片的路径
                    String path = mCursor.getString(mCursor
                            .getColumnIndex(MediaStore.Images.Media.DATA));
                    images.add(path);
                }
                images.add("相机");
                Collections.reverse(images);
                //通知Handler扫描图片完成
                Message message = Message.obtain();
                message.what = SCAN_OK;
                message.obj = images;
                mHandler.sendMessage(message);
                mCursor.close();
            }
        });
    }

    //拍照或选择相册后，数据在这里处理
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CAMERA_REQUEST_CODE:   // 调用相机拍照
                    File temp = new File(mTempPhotoPath);
                    startCropActivity(Uri.fromFile(temp));
                    break;
                case UCrop.REQUEST_CROP:    // 裁剪图片结果
                    handleCropResult(data);
                    break;
                case UCrop.RESULT_ERROR:    // 裁剪图片错误
                    handleCropError(data);
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startCropActivity(Uri uri) {
        UCrop.of(uri, mDestinationUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(512, 512)
                .withTargetActivity(CropActivity.class)
                .start(this);
    }

    /**
     * 处理剪切成功的返回值
     *
     * @param result
     */
    private void handleCropResult(Intent result) {
        deleteTempPhotoFile();
        final Uri resultUri = UCrop.getOutput(result);
        if (null != resultUri) {
            setResult(RESULT_OK, new Intent().putExtra(UCrop.EXTRA_OUTPUT_URI, resultUri));
            finish();
        } else {
            Toast.makeText(this, "无法剪切选择图片", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 处理剪切失败的返回值
     *
     * @param result
     */
    private void handleCropError(Intent result) {
        deleteTempPhotoFile();
        final Throwable cropError = UCrop.getError(result);
        if (cropError != null) {
            Toast.makeText(this, cropError.getMessage(), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "无法剪切选择图片", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 删除拍照临时文件
     */
    private void deleteTempPhotoFile() {
        File tempFile = new File(mTempPhotoPath);
        if (tempFile.exists() && tempFile.isFile()) {
            tempFile.delete();
        }
    }

    /**
     * 本地图片适配器
     */
    private final class PicAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private final Context mContext;
        private List<String> filePath;

        public PicAdapter(Context context, List<String> data) {
            super();
            filePath = data;
            mContext = context;
        }

        @Override
        public int getItemCount() {
            return filePath.size() ;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
            ChildViewHolder holder = (ChildViewHolder) viewHolder;

            if (position == 0) {
                holder.goodPic.setImageResource(R.mipmap.icon_add_photo);
            } else {
                Glide.with(mContext).load(filePath.get(position))
                        .dontAnimate()
                        .thumbnail(0.5f)
                        .placeholder(R.mipmap.icon_empty)
                        .into(holder.goodPic);
            }

        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewHolder, int position) {
            ImageView imageView = new ImageView(mContext);
            imageView.setBackgroundColor(Color.parseColor("#393A3E"));
            return new ChildViewHolder(imageView);
        }
    }

    final class ChildViewHolder extends RecyclerView.ViewHolder {
        public ImageView goodPic;

        public ChildViewHolder(View view) {
            super(view);
            goodPic = (ImageView) view;
        }

    }
}
